<template>
    <div class="stat">
        <Title :title="statData"></Title>
        <StatisticsSearch
            v-if="Object.entries(statData).length !== 0"
            :options="statisOptions"
            :is-end="isEnd"
            :activity-day="activityDay"
            @submit="onSubmit" />
        <BasicData :basic-data="basicData"></BasicData>
        <LineCard ref="lineCard" :line-data="lineData" @exportData="exportLine"></LineCard>
        <div class="preOuter">
            <PreCard :title="`${'客户来源占比'}`" :browse-data="customerShare" @exportData="exportShare"></PreCard>
            <PreCard :title="`${'客户流失占比'}`" :browse-data="customerLoss" @exportData="exportLoss"></PreCard>
        </div>
        <!-- 客户扫码添加时段展示隐藏，后期会放开 -->
        <!-- <div style="margin-top: 16px">
            <PreCard :title="`${'客户扫码添加时段'}`" :browse-data="customerTime" @exportData="exportTime"></PreCard>
        </div> -->
        <el-card class="tableCard" style="margin-top: 16px" shadow="never">
            <Table class="table" :info-data="infoData" @exportData="exportData" @SortData="sortData"></Table>
            <div class="pagination_box">
                <ZWPagination @submit="page"></ZWPagination>
            </div>
        </el-card>
        <div class="title-time">数据统计截止昨日 23:59:59</div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from '@/store';
import Title from './components/Title.vue';
import BasicData from './components/BasicData.vue';
import LineCard from './components/LineCard.vue';
import PreCard from './components/PreCard.vue';
import Table from './components/Table.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import StatisticsSearch from '@/components/zw/statistics-search2.0/StatisticsSearch.vue';
import {
    channelDials,
    exportTable,
    statsBaseInfo,
    statsBase,
    statsTrend,
    statsUserProportion,
    statsScan,
    statsScanExport,
    lossProportionExport,
    sourceProportionExport,
    statsTrendExport
} from '@/api/smartMarketing/drainage/channelCode/index';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';
import { ElMessage } from 'element-plus';

const route = useRoute();
const store = useStore();
const statId = ref(route.query.id);
const lineCard = ref();
const statData = ref({}); // 数据概览
const infoData = ref([]); //详细数据
const basicData = ref([]); // 数据统计
const lineData = ref([]); // 客户趋势图
const customerShare = ref({}); // 客户来源占比
const customerLoss = ref({}); // 客户流失占比
const customerTime = ref({}); // 客户浏览时间段
const activityDay = ref<any>([]); // 活动开始时间
const activity_status = ref(); // 活动状态
const scan = ref([]);
const custlose = ref([]);
const detailParams = ref({
    activity_id: statId.value,
    page: 1,
    page_size: 15,
    order: 1,
    sort: 1
});
const paramsData = reactive({
    activity_id: statId.value,
    create_time: [],
    work_user_id: []
});
const isEnd = computed(() => {
    return [3, 4].includes(Number(activity_status.value));
});

const statisOptions = computed(() => [
    {
        label: '时间筛选',
        type: 'dateFilter',
        currentId: isEnd.value ? 3 : 1
    },
    {
        label: '成员筛选',
        type: 'depart',
        key: 'depart',
        popperClass: 'zw-hide_select_option',
        placeholder: '选择员工',
        multiple: true,
        isMember: true
    }
]);
// 表格查询
const onSubmit = (data: any) => {
    paramsData.create_time = data.times || [];
    paramsData.work_user_id = data.depart || [];
    nextTick(() => {
        initData(paramsData);
        tableApi();
    });
};
// 客户趋势导出
const exportLine = e => {
    statsTrendExport(paramsData)
        .then(() => {
            parabolaAnimation(e);
            ShowTaskMessage('导出异步任务创建成功');
        })
        .catch((e: any) => {
            ElMessage.error(e);
        });
};
// 客户来原占比
const exportShare = e => {
    sourceProportionExport(paramsData)
        .then(() => {
            parabolaAnimation(e);
            ShowTaskMessage('导出异步任务创建成功');
        })
        .catch((e: any) => {
            ElMessage.error(e);
        });
};
// 导出客户流失
const exportLoss = e => {
    lossProportionExport(paramsData)
        .then(() => {
            parabolaAnimation(e);
            ShowTaskMessage('导出异步任务创建成功');
        })
        .catch((e: any) => {
            ElMessage.error(e);
        });
};
// 导出浏览时间
const exportTime = () => {
    statsScanExport(paramsData)
        .then(() => {
            ShowTaskMessage('导出异步任务创建成功');
        })
        .catch((e: any) => {
            ElMessage.error(e);
        });
};
//导出详细数据
const exportData = e => {
    exportTable({ ...detailParams.value, ...paramsData })
        .then((res: any) => {
            parabolaAnimation(e);
            ShowTaskMessage('导出异步任务创建成功');
        })
        .catch((e: any) => {
            ElMessage.error(e);
        });
};
//排序
const sortData = (params: any) => {
    detailParams.value.sort = params.sort;
    detailParams.value.order = params.order;
    tableApi();
};
const submit = (data: any) => {
    lineCard.value.custId = 1;
    getData();
    tableApi();
};
const dataFun = (data: string, name: string, val: string) => {
    const arr = [];
    data.map((i: any) => {
        if (i[val] != 0) {
            arr.push({ name: i[name], value: i[val] });
        }
    });
    return arr;
};
const initData = async (params: any) => {
    const promiseValues = [statsBase(params), statsTrend(params), statsUserProportion(params), statsScan(params)];

    const res = await Promise.all(promiseValues);
    basicData.value = res[0];
    lineData.value = res[1];
    customerShare.value = dataFun(res[2], 'work_user_name', 'get_cust_qty');
    customerLoss.value = dataFun(res[2], 'work_user_name', 'loss_cust_qty');
    customerTime.value = dataFun(res[3], 'time', 'total');
};
const getData = async () => {
    const result = await statsBaseInfo({ activity_id: statId.value });
    statData.value = result;
    activity_status.value = result.activity_status;
    activityDay.value = [result.real_begin_date, result.real_end_date];
};
const tableApi = () => {
    const tableParams = {
        ...detailParams.value,
        ...paramsData
    };
    channelDials(tableParams).then((res: any) => {
        infoData.value = res.list;
        store.dispatch('pageTotal', res.total);
    });
};
const page = (res: any) => {
    detailParams.value.page = res.page;
    detailParams.value.page_size = res.page_size;
    tableApi();
};

onMounted(() => {
    getData();
});
</script>

<style lang="scss" scoped>
.stat {
    .heder_card {
        padding: 17px 20px;
    }

    .preOuter {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        column-gap: 16px;
        align-items: center;
        margin-top: 16px;
    }

    :deep(.tableCard) {
        .el-card__body {
            padding: 0;
        }

        .pagination_box {
            padding: 0 24px 24px;
        }
    }
}

.title-time {
    padding-top: 16px;
    font-size: 16px;
    font-family: PingFangSC-Regular, 'PingFang SC';
    font-weight: 400;
    color: #999;
    line-height: 22px;
}
</style>
